#!/bin/bash

# 生产环境测试脚本
echo "=== 生产环境部署测试 ==="

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker未运行，请先启动Docker"
    exit 1
fi

echo "✅ Docker运行正常"

# 检查配置文件
echo "📋 检查配置文件..."

# 检查并创建生产环境配置
if [ ! -f ".env" ]; then
    echo "⚠️  生产环境配置文件 .env 不存在，创建默认配置..."
    cp .env.dev .env
    # 修改生产环境配置
    sed -i 's/DEBUG=True/DEBUG=False/' .env
    sed -i 's/NODE_ENV=development/NODE_ENV=production/' .env
    sed -i 's/NEXT_PUBLIC_API_URL=http:\/\/localhost:8000/NEXT_PUBLIC_API_URL=/' .env
    sed -i 's/CORS_ORIGIN_WHITELIST=http:\/\/localhost:3000,http:\/\/127.0.0.1:3000,http:\/\/localhost:8000/CORS_ORIGIN_WHITELIST=http:\/\/localhost,http:\/\/127.0.0.1/' .env
fi

echo "✅ 使用生产环境配置文件 .env"

if [ ! -f "nginx/nginx.conf" ]; then
    echo "❌ nginx配置文件不存在"
    exit 1
fi

if [ ! -f "docker-compose.yml" ]; then
    echo "❌ docker-compose.yml不存在"
    exit 1
fi

echo "✅ 配置文件检查完成"

# 启动服务
echo "🚀 启动生产环境..."
docker-compose down 

# 清理可能存在的网络冲突
echo "🔧 清理Docker网络..."
docker network prune -f

# 检查并清理可能冲突的网络
if docker network ls | grep -q "plant_network"; then
    echo "⚠️  发现已存在的 plant_network，尝试清理..."
    docker network rm plant_network 2>/dev/null || true
fi

docker-compose up --build -d

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 60

# 检查网络状态
echo "🌐 检查Docker网络..."
if docker network ls | grep -q "plant_network"; then
    echo "✅ plant_network 网络已创建"
    docker network inspect plant_network --format='{{.Name}}: {{.Driver}}'
else
    echo "❌ plant_network 网络未找到"
    echo "📋 当前网络列表:"
    docker network ls
    exit 1
fi

# 检查后端是否完全启动
echo "🔍 检查后端启动状态..."
for i in {1..30}; do
    if docker-compose logs backend | grep -q "启动Django生产服务器"; then
        echo "✅ 后端启动完成"
        break
    fi
    if [ $i -eq 30 ]; then
        echo "❌ 后端启动超时，查看日志："
        docker-compose logs backend --tail=20
        exit 1
    fi
    sleep 2
done

# 检查服务状态
echo "📊 检查服务状态..."
docker-compose ps

# 检查容器网络连接
echo "🔗 检查容器网络连接..."
for service in backend frontend nginx db redis; do
    if docker-compose ps | grep -q "$service.*Up"; then
        container_name=$(docker-compose ps -q $service)
        if [ ! -z "$container_name" ]; then
            network_info=$(docker inspect $container_name --format='{{range $net, $config := .NetworkSettings.Networks}}{{$net}} {{end}}')
            echo "✅ $service: $network_info"
        fi
    else
        echo "❌ $service: 未运行"
    fi
done

# 测试各个端点
echo "🧪 测试各个端点..."

# 等待nginx完全启动
sleep 10

# 测试主页
if curl -s -o /dev/null -w "%{http_code}" http://localhost | grep -q "200\|301\|302"; then
    echo "✅ 前端主页正常"
else
    echo "❌ 前端主页访问失败"
fi

# 测试API端点
if curl -s -o /dev/null -w "%{http_code}" http://localhost/api/auth/institutions/ | grep -q "200\|401\|403"; then
    echo "✅ API端点正常"
else
    echo "❌ API端点访问失败"
fi

# 测试Admin
if curl -s -o /dev/null -w "%{http_code}" http://localhost/admin/ | grep -q "200\|301\|302"; then
    echo "✅ Admin后台正常"
else
    echo "❌ Admin后台访问失败"
fi

# 测试健康检查
if curl -s http://localhost/health | grep -q "healthy"; then
    echo "✅ 健康检查正常"
else
    echo "❌ 健康检查失败"
fi

echo ""
echo "=== 测试完成 ==="
echo "🌐 访问地址:"
echo "   前端: http://localhost"
echo "   Admin: http://localhost/admin/"
echo "   API: http://localhost/api/"
echo ""
echo "🔍 网络信息:"
docker network inspect plant_network --format='{{.Name}}: {{len .Containers}} 个容器连接'
echo ""
echo "📝 如有问题，请查看日志:"
echo "   docker-compose logs nginx"
echo "   docker-compose logs backend"
echo "   docker-compose logs frontend"
echo "   docker network ls  # 查看网络状态"